<?php
namespace Classes;

class Filter {
    public $searchText;
    protected $attributIds;
    protected $where;
    
    public function getWhere() {
        if($this->attributIds) {
            return $this->where.' AND aa.id_attribut IN('.$this->attributIds.')';
        } else {
            return $this->where;
        }
    }
    
    public function setStatut(Array $statut) {
        if(is_numeric($statut['current'])) {
            $this->where = 'a.statut IN('.$statut['current'].')';
        } else {
            $this->where = 'a.statut IN('.$statut['all'].')';
        }
    }
    
    /**
     * Retourne le texte recherché
     * @return string $find
     */
    public function setSearch($attributIds) {
        $search = null;
        if(isset($_POST['search']) && $_POST['search'] != '') {
            $search = $_POST['search'];
            $this->searchQuery($attributIds, $search);
        }       
        $this->searchText = $search;
    }
    
    /**
     * Retourne la clause where pour une recherche d'annonces
     * @param type $attributIds : Ids des attributs pouvant être recherchés
     * @param type $text : Mots clés à rechercher
     * @return string $where
     */
    private function searchQuery($attributIds, $text) {
        $text = strtolower($text);
        $words = str_replace('+', ' ', trim($text));
        $words = str_replace('\'', ' ', $words);
        $words = str_replace(',', ' ', $words);
        $words = str_replace(':', ' ', $words);
        
        $wordsArray = explode(' ', $words);
        
        //$where = '(aa.value LIKE "%'.$text.'%")';
        $nbWords = count($wordsArray);
        
        // Tous les mots sont à trouver
        $count = 0;
        foreach($wordsArray as $word) {
            if($count == 0) {
                $where = ' AND ((aa.value LIKE "%'.$word.'%"';
            } else {
                $where .= ' AND aa.value LIKE "%'.$word.'%"';
            }
            $count++;
        }
        if($count == $nbWords) {
            $where .= ')';
        }
        
        // Au moins un seul mot est à trouver
        $count = 0;
        foreach($wordsArray as $word) {
            if($count == 0) {
                $where .= ' OR (aa.value LIKE "%'.$word.'%"';
            } else {
                $where .= ' OR aa.value LIKE "%'.$word.'%"';
            }
            $count++;
        }
        if($count == $nbWords) {
            $where .= '))';
        }
        
        $this->attributIds = $attributIds;
        $this->where .= $where;
    }
    
    /**
     * Afficher un champ de recherche
     * @param type $value : Valeur du champ si elle existe
     * @return string $output
     */
    public function displaySearchField($value='') {
        $output = '<script type="text/javascript">'
                . 'function processSearch() {'
                . 'var inputSearch = document.getElementById("search");'
                . 'if(inputSearch.value != "") {'
                . 'document.forms["filter-form"].submit();'
                . '}'
                . '}'
                . 'function resetSearch() {'
                . 'var inputSearch = document.getElementById("search");'
                . 'if(inputSearch.value != "") {'
                . 'inputSearch.value = "";'
                . 'document.forms["filter-form"].submit();'
                . '}'
                . '}'
                . '</script>'
                . '<input type="text" name="search" id="search" class="" value="'.(($value)?$value:'').'" />&nbsp;'
                . '<button name="searchSubmit" class="btn btn-xs btn-primary" onclick="processSearch()">Rechercher</button>&nbsp;'
                . '<button name="searchReset" class="btn btn-xs btn-default" onclick="resetSearch()">Réinitialiser</button>';
        return $output;
    }
}